import errno
import os
import time
import posixpath

from bottle import route, template, request, static_file
from config import config
from mondb import conn

logRoot = config['path.log_root']


@route('/')
def index():
    if not os.path.isdir(logRoot):
        return 'No files uploaded yet'
    filenames = []
    for file in os.listdir(logRoot):
        if file.endswith('.txt'):
            filenames.append(file)
    return template('make_table', template_lookup=[config['path.template_root']], filenames=filenames)


@route('/logs/<filename>')
def static(filename):
    return static_file(filename, root=logRoot)


@route('/upload', method='POST')
def upload():
    body = request.body.getvalue()
    request.body.close()
    filename = logRoot + str(int(time.time() * 1000)) + '.txt'
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
    with open(filename, 'w') as file:
        file.write(body)
    return 'success'


@route('/latency', method='POST')
def latency():
    record = request.json
    # print(record)
    if 'type_name' in record:
        record["timestamp"] = int(time.time() * 1000)
        platform_info = record['PlatformInfo']

        device_id = platform_info["DeviceID"] if "DeviceID" in platform_info else ""
        os_info = platform_info["OSInfo"]

        if "MacAddress" in platform_info:
            device_id = platform_info["MacAddress"]
            platform_info["DeviceID"] = device_id

        record["DeviceID"] = device_id
        record["OSInfo"] = os_info
        del record["PlatformInfo"]
        res = conn.record.insert_one(record)
        print('inserted: ', res.inserted_id)

        device = conn.device.find_one({"DeviceID": device_id, "OSInfo": os_info})
        if device is None:
            conn.device.insert_one(platform_info)

    return 'success'


@route('/charts/<path:path>')
def callback(path):
    base, ext = posixpath.splitext(path)
    ext_mine = {
        '.js': 'application/javascript',
    }
    if ext in ext_mine:
        return static_file(path, root=config['path.charts_root'], mimetype=ext_mine[ext])
    return static_file(path, root=config['path.charts_root'])


@route('/api/get_device_test_list')
def callback():
    devices = conn.device.find()
    device_list = []
    for device in devices:
        del device['_id']
        if 'Chip' in device:
            del device['Chip']
        if 'GPUInfo' in device:
            del device['GPUInfo']
        device_list.append(device)

    tests = conn.type.find()
    test_list = []
    for test in tests:
        del test['_id']
        test_list.append(test)
    return {"device_list": device_list, "test_list": test_list}


@route('/api/get_latency_data', method='POST')
def callback():
    params = request.json
    records = conn.record.find({"DeviceID": params['device_id'], "type_name": params['type_name']})
    ret = []
    i = 0
    for record in records:
        _id = str(record['_id'])
        del record['_id']
        del record['type_name']
        del record['DeviceID']
        del record['OSInfo']
        if "version" not in record and "FPS" in record:
            fps = record['FPS']
            record['version'] = "android" if int(fps) == fps else "Unreal 5.1.1"
        ret.insert(i, record)
        i += 1
    return {"data": ret}
